local Msg = require("core.Msg")
local Level3366Excel = require("excel.Yellow").level3366
local Grid = require("bag.Grid")
local BagLogic = require("bag.BagLogic")
local Lang = require("common.Lang")
local PfLogic = require("tencentApi.PfLogic")
local Broadcast = require("broadcast.Broadcast")


local function getStatus(human, id)
    if not PfLogic.is3366Show(human) then
        return 0
    end
    local conf = Level3366Excel[id]
    if not conf then
        return 2
    end
    if id > 6 then
        return 2
    end
    if human.db.level3366CanGet[id-1]  == 1 then
        return 2
    end
    if conf.minlv <= human.db.level3366 and (conf.maxlv == -1 or conf.maxlv >= human.db.level3366) then
       return 1
    else
        return 0
    end
end
RewardGridCache = nil
function sendLevel3366Config(human)
    local m = Msg.gc.GC_LEVEL_3366_REWARD_QUERY
    if m.list[0] == nil then
        m.list[0] = 0
    end
    if not RewardGridCache then
        RewardGridCache = {}
        m.list[0] = 0
        for i = 1, #Level3366Excel do
            RewardGridCache[i] = {}
            local conf = Level3366Excel[i]
            local rewardCnt = #conf.reward 
            if rewardCnt > 5 then
                rewardCnt = 5
            end
            for j = 1, rewardCnt do
                local g = {}
                Grid.create(g, conf.reward[j][1], conf.reward[j][2], true)
                Grid.makeItem(g, m.list[i].reward[j])      
                RewardGridCache[i][j] = g          
            end
            m.list[i].id = i
            m.list[i].minLv = conf.minlv
            m.list[i].maxLv = conf.maxlv
            m.list[i].reward[0] = rewardCnt
            
            m.list[0] = m.list[0] + 1
            if i == 10 then
                break
            end
        end        
    end
    for i = 1, m.list[0] do
        m.list[i].status = getStatus(human, m.list[i].id)
    end    
    Msg.send(m, human.fd)
end


function getReward(human, id)
    local conf = Level3366Excel[id]
    if not conf then
        return
    end
    local status = getStatus(human, id)    
    if status ~= 1 then
        return
    end
    
    if BagLogic.getLeftGrids(human) < #RewardGridCache[id] then
       Broadcast.sendBroadcast(human, Lang.MOUSE, Lang.BAG_FULL)
       return
    end
    human.db.level3366CanGet[id-1] = 1
    
    for i = 1, #RewardGridCache[id] do
      BagLogic.addItem(human, RewardGridCache[id][i].id,RewardGridCache[id][i].bind,RewardGridCache[id][i].cnt, "level3366")
    end
    
    local msg = Msg.gc.GC_LEVEL_3366_REWARD_GET
    msg.id = id
    msg.status = 2
    Msg.send(msg, human.fd)   
end